//
//  RefreshBaseView.swift
//  MySwiftPullToRefresh
//
//  Created by likai on 2017/5/2.
//  Copyright © 2017年 terry. All rights reserved.
//

import UIKit
//http://www.jianshu.com/p/604305a61e57  fileprivate和open
//
open class RefreshBaseView: UIView {
    var scrollView: UIScrollView?{
        return superview as? UIScrollView //获取到父视图,认为父视图为ScrollView.
    }
    
    private var panGestureRecongizer: UIPanGestureRecognizer?
    
    //当本视图的父类视图改变的时候,系统会自动的执行这个方法.newSuperview是本视图的新父类视图.newSuperview有可能是nil
    open override func willMove(toSuperview newSuperview: UIView?) {
        scrollView?.removeObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset))
        panGestureRecongizer?.removeObserver(self, forKeyPath: #keyPath(UIPanGestureRecognizer.state))
        
    }
    
    open override func didMoveToSuperview() {
        
        //用KVO监听scrollView的contentOffset(偏移量) 和 手势
        scrollView?.addObserver(self, forKeyPath: #keyPath(UIScrollView.contentOffset), context: nil)
        
        panGestureRecongizer = scrollView?.panGestureRecognizer
        panGestureRecongizer?.addObserver(self, forKeyPath: #keyPath(UIPanGestureRecognizer.state), context: nil)
        
        
    }
    
    open override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        
        guard let scrollView = scrollView else{
            return
        }
        if keyPath == #keyPath(UIScrollView.contentOffset) {
            scrollViewDidScroll(scrollView)
        }
        if keyPath == #keyPath(UIPanGestureRecognizer.state) {
            if case .ended = scrollView.panGestureRecognizer.state {
                scrollViewWillEndDragging(scrollView)
            }
        }
        
        
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView){
        fatalError("SwiftPullToRefresh: should use RefreshHeaderView or RefreshFooterView")
        
    }
    
    func scrollViewWillEndDragging(_ scrollView: UIScrollView){
        fatalError("SwiftPullToRefresh: should use RefreshHeaderView or RefreshFooterView")
    }
    

}
